<template>
  <el-container class="coupon-view panel-block">
    <el-header class="sa-header">
        <el-row class="sa-m-t-20" :gutter="20">
          <el-col v-for="(value, key) in dashboard" :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <div class="card">
                  <div class="sa-flex sa-row-between sa-m-b-4">
                      <div class="num">{{ value.num }}</div>
                  </div>
                  <div class="sa-flex sa-row-between">
                      <div class="name">{{ value.name }}</div>
                      <el-popover popper-class="sa-popper" trigger="hover">
                          {{ value.tip }}
                          <template #reference>
                              <el-icon class="tip">
                                  <warning />
                              </el-icon>
                          </template>
                      </el-popover>
                  </div>
              </div>
          </el-col>
      </el-row>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">
          <span class="left">{{ title }}</span>
          <search-condition
            :conditionLabel="filterParams.conditionLabel"
            @deleteFilter="deleteFilter"
          ></search-condition>
        </div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button class="sa-button-refresh" icon="Search" @click="openFilter"></el-button>
          <el-button v-auth="'shop.admin.coupon.add'" type="primary" icon="Plus" @click="addRow"
            >添加</el-button
          >
          <el-button
            v-auth="'shop.admin.coupon.recyclebin'"
            type="danger"
            icon="Delete"
            plain
            @click="openRecyclebin"
            >回收站</el-button
          >
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0" v-loading="loading">
      <el-table height="100%" class="sa-table" :data="table.data" stripe>
        <template #empty>
          <sa-empty />
        </template>
        <el-table-column prop="id" label="ID" min-width="88" sortable></el-table-column>
        <el-table-column label="优惠券名称" min-width="172">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="类型" min-width="74">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.type_text }}</div>
          </template>
        </el-table-column>
        <el-table-column label="可用范围" min-width="116">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.use_scope_text }}</div>
          </template>
        </el-table-column>
        <el-table-column label="优惠内容" min-width="214">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.amount_text }}</div>
          </template>
        </el-table-column>
        <el-table-column label="领取状态" min-width="80" align="center">
          <template #default="scope">
            <el-popover
              placement="bottom"
              title="优惠券有效期"
              trigger="hover"
              popper-class="sa-popper"
            >
              <template #reference>
                <div
                  class="sa-table-line-1 get-time-text"
                  :class="
                    scope.row.get_time_text == '发放中'
                      ? 'success'
                      : scope.row.get_time_text == '已结束'
                      ? 'sa-delete'
                      : 'info'
                  "
                >
                  {{ scope.row.get_time_text }}
                </div>
              </template>
              <div v-if="scope.row.use_time_type == 'days'">
                领取{{ scope.row.start_days }}天后生效，有效期{{ scope.row.days }}天
              </div>
              <div v-if="scope.row.use_time_type == 'range'">
                <div>开始时间：{{ scope.row.use_start_time }}</div>
                <div>结束时间：{{ scope.row.use_end_time }}</div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="已领取" min-width="96">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.get_num }}</div>
          </template>
        </el-table-column>
        <el-table-column label="已使用" min-width="96">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.use_num }}</div>
          </template>
        </el-table-column>
        <el-table-column label="剩余" min-width="96">
          <template #default="scope">
            <div class="sa-table-line-1">{{ scope.row.stock }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="130">
          <template #default="scope">
            <el-dropdown trigger="click" @command="handleCommand">
              <el-button v-auth="'shop.admin.coupon.edit'" class="status-btn">
                {{ scope.row.status_text }}
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :command="{
                      id: scope.row.id,
                      type: 'normal',
                    }"
                  >
                    <!-- TODO-jj：弹框提醒 -->
                    公开发放
                    <!-- <template #default>
                      <el-popconfirm width="fit-content"
                        confirm-button-text="确认"
                        cancel-button-text="取消"
                        title="确认删除这条记录?"
                        @confirm="handConfirm(scope.row.id)"
                      >
                        <template #reference>
                          <el-button class="sa-button" text> 公开发放 </el-button>
                        </template>
                      </el-popconfirm>
                    </template> -->
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{
                      id: scope.row.id,
                      type: 'hidden',
                    }"
                    >后台发放</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="{
                      id: scope.row.id,
                      type: 'disabled',
                    }"
                    >禁止使用</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="260" fixed="right">
          <template #default="scope">
            <el-button
              v-auth="'shop.admin.coupon.send'"
              type="primary"
              link
              @click="onSend(scope.row.id)"
              >手动发放</el-button
            >
            <el-button
              v-auth="'shop.admin.user.coupon.couponlist'"
              type="primary"
              link
              @click="onCoupon(scope.row.id)"
              >领取记录</el-button
            >
            <el-button
              v-auth="'shop.admin.coupon.detail'"
              class="is-link"
              type="primary"
              @click="editRow(scope.row.id)"
              >编辑</el-button
            >
            <el-popconfirm
              width="fit-content"
              confirm-button-text="确认"
              cancel-button-text="取消"
              title="确认删除这条记录?"
              @confirm="deleteRow(scope.row.id)"
            >
              <template #reference>
                <el-button v-auth="'shop.admin.coupon.delete'" class="is-link" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <sa-view-bar>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { api } from './coupon.service';
  import { useModal, usePagination } from '@/sheep/hooks';
  import { useSearch } from '@/sheep/components/sa-table/sa-search/useSearch';
  import { composeFilter } from '@/sheep/utils';
  import CouponEdit from './edit.vue';
  import ApiRecyclebin from './recyclebin.vue';
  import { cloneDeep } from 'lodash';
  import { useRouter, useRoute } from 'vue-router';
  import UserSelect from '@/app/user/admin/select.vue';

  const router = useRouter();

  const filterParams = reactive({
    tools: {
      keyword: {
        type: 'tinput',
        field: 'keyword',
        value: '',
        label: '搜索内容',
        placeholder: '请输入查询内容',
      },
      type: {
        type: 'tselect',
        label: '类型',
        field: 'type',
        value: '',
        options: {
          data: [
            {
              label: '满减券',
              value: 'reduce',
            },
            {
              label: '折扣券',
              value: 'discount',
            },
          ],
        },
      },
      use_scope: {
        type: 'tselect',
        label: '可用范围',
        field: 'use_scope',
        value: '',
        options: {
          data: [
            {
              label: '全场通用',
              value: 'all_use',
            },
            {
              label: '指定商品可用',
              value: 'goods',
            },
            {
              label: '指定商品不可用',
              value: 'disabled_goods',
            },
            {
              label: '指定分类可用',
              value: 'category',
            },
          ],
        },
      },
    },
    data: {
      keyword: '',
      type: '',
      use_scope: '',
    },
    conditionLabel: {},
  });
  const { openFilter, deleteFilter } = useSearch({ filterParams, getData });

  const dashboard = reactive({
    total_num: {
      name: '总发券量/张',
      num: '',
      tip: '用户领取的优惠券的总张数，包含已经被后台删除的优惠券'
    },
    expire_num: {
      name: '已过期/张',
      num: '',
      tip: '用户已领取的并且已经超过可使用日期的未使用优惠券'
    },
    use_num: {
      name: '已使用/张',
      num: '',
      tip: '用户已领取并且已使用的优惠券',
    },
    use_percent: {
      name: '使用率',
      num: '',
      tip: '用户已使用优惠和总发券量的比例'
    },
  })

  // 表格
  const table = reactive({
    data: [],
    order: '',
    sort: '',
    selected: [],
  });
  // 分页
  const { pageData } = usePagination();
  const loading = ref(true);
  const title = ref('优惠券');
  const statusId = ref(0);
  function handConfirm(e) {
    statusId.value = e;
  }

  //获取状态
  async function handleCommand(e) {
    await api.edit(e.id, {
      status: e.type,
    });
    getData();
  }
  // 获取数据
  async function getData(page) {
    loading.value = true;
    if (page) pageData.page = page;
    let tempSearch = cloneDeep(filterParams.data);
    let search = composeFilter(tempSearch);
    const { data } = await api.list({
      page: pageData.page,
      list_rows: pageData.list_rows,
      ...search,
    });
    table.data = data.coupons.data;
    pageData.page = data.coupons.current_page;
    pageData.list_rows = data.coupons.per_page;
    pageData.total = data.coupons.total;

    for (var key in dashboard) {
      dashboard[key].num = data[key]
    }

    loading.value = false;
  }

  function addRow() {
    useModal(
      CouponEdit,
      {
        title: `添加${title.value}`,
        type: 'add',
        atype: 'full_coupon',
      },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }
  function editRow(id) {
    useModal(
      CouponEdit,
      {
        title: `编辑${title.value}`,
        type: 'edit',
        atype: 'full_coupon',
        id: id,
      },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }
  async function deleteRow(id) {
    await api.delete(id);
    getData();
  }
  function openRecyclebin() {
    useModal(
      ApiRecyclebin,
      {
        title: '回收站',
      },
      {
        confirm: () => {
          getData();
        },
        close: () => {
          getData();
        },
      },
    );
  }

  function onCoupon(id) {
    router.push({
        path: '/shop/admin/user/couponList',
        query: {
          couponid: id,
        },
      });
  }

  function onSend(id) {
    useModal(
      UserSelect,
      {
        title: `选择用户`,
        id: id,
      },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }

  onMounted(() => {
    getData();
  });
</script>
<style lang="scss" scoped>
  .coupon-view {

    .card {
        height: 80px;
        background: var(--sa-background-assist);
        border: 1px solid var(--sa-space);
        box-shadow: 0px 2px 6px rgba(140, 140, 140, 0.12);
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;
    }

    .card .num {
        font-weight: 400;
        font-size: 24px;
        line-height: 26px;
        color: var(--sa-subtitle);
    }

    .card .oper {
        font-weight: 400;
        font-size: 12px;
        line-height: 14px;
        color: #FAAD14;
        cursor: pointer;
    }

    .card .name {
        font-weight: 400;
        font-size: 12px;
        line-height: 14px;
        color: var(--sa-font);
    }

    .card .tip {
        font-size: 14px;
        color: var(--sa-subfont);
    }

    .sa-title {
        padding-top: 0;
    }
  }
  .get-time-text {
    text-align: center;
  }

  .status-btn {
    background-color: var(--sa-space);
    color: var(--sa-subfont);
    border: none;
  }
  .success {
    color: #52c41a;
  }

  .info {
    color: #999999;
  }
</style>
